package personalProfile;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.Calendar;
import java.util.ResourceBundle;

import javax.swing.ImageIcon;

import managers.DBManager;
import managers.socialNetworkManagers.CacheManager;
import managers.socialNetworkManagers.SocialNetworkManager;
import spotGUI.personalProfileGUI.PersonalProfileFrame;
import spotGUI.personalProfileGUI.ProfileUpdateLogger;
import spotGUI.personalProfileGUI.Updatable;
import utils.ImageUtils;
import utils.SocialUserData;
import utils.StackTracePrinter;

public class PersonalProfile implements Updatable {

	public static final int MINIATURE_WIDTH = 48;
	
	private PersonalProfileFrame frame;
	private static ProfileUpdateLogger logger = new ProfileUpdateLogger();

	private int userId;

	private PersonalDataManager personalDataManager;
	private FamilyManager familyManager;
	private PhotoManager photoManager;

	public PersonalProfile (int id) {

		userId = id;

		personalDataManager = new PersonalDataManager(id, logger);
		familyManager = new FamilyManager(id, logger);
		photoManager = new PhotoManager(id, logger);

		frame = new PersonalProfileFrame (this);
		frame.setVisible(true);
	}

	public PersonalProfileFrame getFrame() {
		return frame;
	}

	public ProfileUpdateLogger getLogger() {
		return logger;
	}

	public PersonalDataManager getPersonalDataManager() {
		return personalDataManager;
	}

	public FamilyManager getFamilyManager() {
		return familyManager;
	}

	public PhotoManager getPhotoManager() {
		return photoManager;
	}

	public int getUserId() {
		return userId;
	}

	public ImageIcon retrievePersonalPhoto(Connection conn) throws IOException, SQLException {

		Statement stmt = conn.createStatement();
		String query = "select lastphotoupdate from spotmessenger.USERS where id = "+userId;
		ResultSet rs = stmt.executeQuery(query);
		rs.next();
		ImageIcon photo = CacheManager.retrieveImage(CacheManager.formatPersonalPhotoName(userId, CacheManager.MEDIUM), rs.getTimestamp(1));
		DBManager.closeResources(stmt, rs);
		if (photo != null) {
			return photo;
		} else {
			Statement stmt2 = conn.createStatement();
			String query2 = "select photo from spotmessenger.USERS where id = "+userId;
			ResultSet rs2 = stmt2.executeQuery(query2);
			rs2.next();
			ImageIcon photo2 = ImageUtils.bytesToImage(rs2.getBytes(1), "/images/Icons/128x128/user.png");
			if (rs2.getBytes(1) != null)
				CacheManager.saveImage(rs2.getBytes(1), CacheManager.formatPersonalPhotoName(userId, CacheManager.MEDIUM));
			DBManager.closeResources(stmt2, rs2);
			return photo2;
		}

	}

	@Override
	public void edit() {
		if (SocialNetworkManager.getSharedInstance().getUserId() == userId)
			frame.makeEditable();
			personalDataManager.edit();
			familyManager.edit();
			photoManager.edit();
	}

	@Override
	public void update() {

		logger.clear();
		
		SocialUserData data = frame.createNewSocialUserData();
		SocialUserData localUserData = SocialNetworkManager.getSharedInstance().getUser(SocialNetworkManager.getSharedInstance().getUserId());
		try {
			Connection conn = DBManager.getConnection();
			PreparedStatement stmt;
			ImageIcon miniature = null;
			
			if (data.getPhoto() == null) {
				stmt = conn.prepareStatement("update spotmessenger.USERS set nicname = ?, mood = ? where id = ?");
				if (data.getNickName() == null)
					stmt.setNull(1, Types.VARCHAR);
				else
					stmt.setString(1, data.getNickName());
				stmt.setString(2, data.getMood());
				stmt.setInt(3, userId);

			} else {
				stmt = conn.prepareStatement("update spotmessenger.USERS set nickname = ?, mood = ?, " +
						"photo = ?, photominiature = ?, lastphotoupdate = ? where id = ?");
				stmt.setString(1, data.getNickName());
				stmt.setString(2, data.getMood());
				ImageUtils.imageToDB(data.getPhoto(), stmt, 3);
				miniature = ImageUtils.resize(data.getPhoto(), MINIATURE_WIDTH, -1);
				ImageUtils.imageToDB(miniature, stmt, 4);
				stmt.setTimestamp(5, new Timestamp(Calendar.getInstance().getTimeInMillis()));
				stmt.setInt(6, userId);
			}
			stmt.executeUpdate();
			
			localUserData.setNickName(data.getNickName());
			localUserData.setMood(data.getMood());
			if (miniature != null)
				localUserData.setPhoto(miniature);
			
			DBManager.closeResources(stmt, null);
			
		} catch (SQLException e) {
			if (e.getErrorCode() == 1062)
				logger.addError(ResourceBundle.getBundle("personalProfile.messages").getString("l.3"));
			else
				logger.addError(ResourceBundle.getBundle("personalProfile.messages").getString("l.4"));
			StackTracePrinter.print(e);
		}

		personalDataManager.update();
		familyManager.update();
		photoManager.update();

		frame.dispose();
		new PersonalProfile(userId);
		
		SocialNetworkManager.getSharedInstance().getFeedbackManager().update();
		
		logger.putOnTop();
	}

}
